package rjeutsky.database.jpa.models;

import java.util.LinkedList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.Session;

import rjeutsky.models.Subscription;

@Entity
@Table(name="Subscription")
public class JPASubscription {
	
	private long id;
	private JPAUser user;
	private List<JPAPayment> payments;
	private List<JPAPublication> publications;
	
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	
	@ManyToOne
	@JoinColumn(name="userId")
	public JPAUser getUser() {
		return user;
	}
	public void setUser(JPAUser user) {
		this.user = user;
	}
	
	@OneToMany(targetEntity=JPAPayment.class, mappedBy="subscription", 
			cascade=CascadeType.ALL)
	public List<JPAPayment> getPayments() {
		return payments;
	}
	public void setPayments(List<JPAPayment> payments) {
		this.payments = payments;
	}
	@ManyToMany
	@JoinTable(name="PublicationSubscription", 
		joinColumns={@JoinColumn(name="subscriptionId")},
		inverseJoinColumns={@JoinColumn(name="publicationId")})
	public List<JPAPublication> getPublications() {
		return publications;
	}
	public void setPublications(List<JPAPublication> publications) {
		this.publications = publications;
	}
	@Transient
	public Subscription getSubscription() {
		Subscription subscription = new Subscription();
		subscription.setId(id);
		subscription.setUserId(user.getId());
		return subscription;
	}
	
	@Transient
	public static JPASubscription getJPASubscription(Session session, Subscription subscription) {
		if (subscription == null) {
			return null;
		}
		
		return (JPASubscription) session.get(JPASubscription.class, subscription.getId());
	}
	
	@Transient
	public static List<Subscription> getSubscriptions(List<JPASubscription> jpaSubscriptions) {
		List<Subscription> subscriptions = new LinkedList<Subscription>();
		if (jpaSubscriptions != null) {
			for (JPASubscription subscription : jpaSubscriptions) {
				subscriptions.add(subscription.getSubscription());
			}
		}
		
		return subscriptions;
	}
}
